package com.jhgsys.internal.hazard.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jhgsys.internal.base.entity.BaseAreaScheduling;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.utils.BeanHelper;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.hazard.dto.HazardExamineTeamDto;
import com.jhgsys.internal.hazard.entity.HazardExamineTeam;
import com.jhgsys.internal.hazard.entity.HazardExamineTeamUser;
import com.jhgsys.internal.hazard.mapper.HazardExamineTeamMapper;
import com.jhgsys.internal.hazard.service.IHazardExamineTeamService;
import com.jhgsys.internal.hazard.service.IHazardExamineTeamUserService;
import com.jhgsys.internal.system.entity.Tenant;
import com.jhgsys.internal.system.service.ITenantService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 *  Service实现
 *
 * @author zhangwei
 * @date 2024-09-02 11:25:48
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class HazardExamineTeamServiceImpl extends ServiceImpl<HazardExamineTeamMapper, HazardExamineTeam> implements IHazardExamineTeamService {
    @Autowired
    private IHazardExamineTeamUserService hazardExamineTeamUserService;
    @Autowired
    private ITenantService tenantService;
    /**
     * 查询（分页）
     * @author zhangwei
     * @date 2024-09-02 11:25:48
     * @param request QueryRequest
     * @param hazardExamineTeam hazardExamineTeam
     * @return IPage<HazardExamineTeam>
    */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public IPage<HazardExamineTeamDto> findHazardExamineTeamPage(QueryRequest request, HazardExamineTeamDto hazardExamineTeamDto) {
        HazardExamineTeam hazardExamineTeam = BeanHelper.copyProperties(hazardExamineTeamDto,HazardExamineTeam.class);
        IPage<HazardExamineTeamDto> result = new  Page<>(request.getPageNum(), request.getPageSize());
        LambdaQueryWrapper<HazardExamineTeam> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HazardExamineTeam::getDeletedFlg, FebsConstant.VALID);
        if(StringUtils.isNotBlank(hazardExamineTeamDto.getRealName())){
            queryWrapper.apply(" examine_team_id in (SELECT examine_team_id FROM hazard_examine_team_user WHERE real_name like '%"+hazardExamineTeamDto.getRealName()+"%' AND deleted_flg = '0') ");
        }
        if(StringUtils.isNotBlank(hazardExamineTeam.getStatus())){
            queryWrapper.eq(HazardExamineTeam::getStatus,hazardExamineTeam.getStatus() );
        }
        if(StringUtils.isNotBlank(hazardExamineTeam.getTenantId())){
            queryWrapper.eq(HazardExamineTeam::getTenantId,hazardExamineTeam.getTenantId() );
        }
        if(StringUtils.isNotBlank(hazardExamineTeam.getTeamName())){
            queryWrapper.like(HazardExamineTeam::getTeamName,hazardExamineTeam.getTeamName());
        }
        queryWrapper.orderByAsc(HazardExamineTeam::getSort);
        Page<HazardExamineTeam> page = new Page<>(request.getPageNum(), request.getPageSize());
        FebsUtil.pageWrapper(page, request);
        IPage<HazardExamineTeam> pages = this.page(page, queryWrapper);
        List<HazardExamineTeam> hazardExamineTeamList = pages.getRecords();
        List<HazardExamineTeamDto> list = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(hazardExamineTeamList)){
            list = BeanHelper.copyWithCollection(hazardExamineTeamList,HazardExamineTeamDto.class);
            String teamIds = list.stream().map(HazardExamineTeamDto::getExamineTeamId).collect(Collectors.joining(","));
            List<HazardExamineTeamUser> users = hazardExamineTeamUserService.findByTeamIds(teamIds);

            list.forEach(d -> {
                List<HazardExamineTeamUser> teamUserList = users.stream().filter(b -> b.getExamineTeamId().equals(d.getExamineTeamId())).collect(Collectors.toList());
                d.setTeamUserList(teamUserList);
            });
        }
        result.setRecords(list);
        result.setTotal(list.size());
        return result;
    }

    /**
     * 查询（所有）
     * @author zhangwei
     * @date 2024-09-02 11:25:48
     * @param hazardExamineTeam hazardExamineTeam
     * @return List<HazardExamineTeam>
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public List<HazardExamineTeam> findHazardExamineTeamList(HazardExamineTeam hazardExamineTeam) {
	    LambdaQueryWrapper<HazardExamineTeam> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HazardExamineTeam::getDeletedFlg, 0);
        if(StringUtils.isNotBlank(hazardExamineTeam.getStatus())){
            queryWrapper.eq(HazardExamineTeam::getStatus,hazardExamineTeam.getStatus() );
        }
        if(StringUtils.isNotBlank(hazardExamineTeam.getTenantId())){
            queryWrapper.eq(HazardExamineTeam::getTenantId,hazardExamineTeam.getTenantId() );
        }
        if(StringUtils.isNotBlank(hazardExamineTeam.getTeamName())){
            queryWrapper.like(HazardExamineTeam::getTeamName,hazardExamineTeam.getTeamName());
        }
		return this.baseMapper.selectList(queryWrapper);
    }

    /**
    * 根据ID查询
    * @author zhangwei
    * @date 2024-09-02 11:25:48
    * @param id
    * @return HazardExamineTeam
    */
    @Override
    public HazardExamineTeamDto findHazardExamineTeamById(String id){
        HazardExamineTeam hazardExamineTeam = this.baseMapper.selectById(id);
        HazardExamineTeamDto hazardExamineTeamDto = BeanHelper.copyProperties(hazardExamineTeam,HazardExamineTeamDto.class);
        //查询组员
        HazardExamineTeamUser hazardExamineTeamUser = new HazardExamineTeamUser();
        hazardExamineTeamUser.setExamineTeamId(hazardExamineTeam.getExamineTeamId());
        List<HazardExamineTeamUser> hazardExamineTeamUserList = hazardExamineTeamUserService.findHazardExamineTeamUserList(hazardExamineTeamUser);
        hazardExamineTeamDto.setTeamUserList(hazardExamineTeamUserList);
        return hazardExamineTeamDto;
    }

    /**
     * 新增
     * @author zhangwei
     * @date 2024-09-02 11:25:48
     * @param hazardExamineTeamDto hazardExamineTeamDto
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public void createHazardExamineTeam(HazardExamineTeamDto hazardExamineTeamDto) {
        HazardExamineTeam hazardExamineTeam = BeanHelper.copyProperties(hazardExamineTeamDto,HazardExamineTeam.class);
        hazardExamineTeam.setCreatedTime(new Date());
        this.save(hazardExamineTeam);
        //保存小组成员 hazard_examine_team_user
        if(CollectionUtils.isNotEmpty(hazardExamineTeamDto.getTeamUserList())){
            hazardExamineTeamDto.setExamineTeamId(hazardExamineTeam.getExamineTeamId());
            saveTeamUsers(hazardExamineTeamDto);
        }
    }

    /**
     * 修改
     * @author zhangwei
     * @date 2024-09-02 11:25:48
     * @param hazardExamineTeamDto hazardExamineTeamDto
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public void updateHazardExamineTeam(HazardExamineTeamDto hazardExamineTeamDto) {
        HazardExamineTeam hazardExamineTeam = BeanHelper.copyProperties(hazardExamineTeamDto,HazardExamineTeam.class);
        hazardExamineTeam.setUpdatedTime(new Date());
        this.saveOrUpdate(hazardExamineTeam);
        //保存小组成员 hazard_examine_team_user
        if(CollectionUtils.isNotEmpty(hazardExamineTeamDto.getTeamUserList())){
            //先删除，再保存
            hazardExamineTeamUserService.deleteByTeamIds(hazardExamineTeamDto.getExamineTeamId());
            if(CollectionUtils.isNotEmpty(hazardExamineTeamDto.getTeamUserList())){
                List<HazardExamineTeamUser> teamUserList = hazardExamineTeamDto.getTeamUserList().stream()
                        .map(d -> {
                            HazardExamineTeamUser hazardExamineTeamUser = BeanHelper.copyProperties(d,HazardExamineTeamUser.class);
                            hazardExamineTeamUser.setExamineTeamId(hazardExamineTeamDto.getExamineTeamId());
                            hazardExamineTeamUser.setCreatedBy(hazardExamineTeamDto.getCreatedBy());
                            hazardExamineTeamUser.setCreatedTime(new Date());
                            hazardExamineTeamUser.setTenantId(hazardExamineTeamDto.getTenantId());
                            return hazardExamineTeamUser;
                        }).collect(Collectors.toList());
                hazardExamineTeamUserService.saveBatch(teamUserList);
            }
        }
    }

    private void saveTeamUsers(HazardExamineTeamDto hazardExamineTeamDto){
        //先删除，再保存
        hazardExamineTeamUserService.deleteByTeamIds(hazardExamineTeamDto.getExamineTeamId());
        if(CollectionUtils.isNotEmpty(hazardExamineTeamDto.getTeamUserList())){
            List<HazardExamineTeamUser> teamUserList = hazardExamineTeamDto.getTeamUserList().stream()
                    .map(d -> {
                        HazardExamineTeamUser hazardExamineTeamUser = BeanHelper.copyProperties(d,HazardExamineTeamUser.class);
                        hazardExamineTeamUser.setExamineTeamId(hazardExamineTeamDto.getExamineTeamId());
                        hazardExamineTeamUser.setCreatedBy(hazardExamineTeamDto.getCreatedBy());
                        hazardExamineTeamUser.setCreatedTime(new Date());
                        hazardExamineTeamUser.setTenantId(hazardExamineTeamDto.getTenantId());
                        return hazardExamineTeamUser;
                    }).collect(Collectors.toList());
            hazardExamineTeamUserService.saveBatch(teamUserList);
        }
    }

    /**
     * 逻辑删除
     * @author zhangwei
     * @date 2024-09-02 11:25:48
     * @param hazardExamineTeam hazardExamineTeam
     * @param hazardExamineTeamIds hazardExamineTeamIds
     */
    @Override
    @Transactional
    public void deleteHazardExamineTeam(HazardExamineTeam hazardExamineTeam,String hazardExamineTeamIds) {
        List<String> list = Arrays.asList(hazardExamineTeamIds.split(StringPool.COMMA));
        this.baseMapper.update(hazardExamineTeam,new LambdaQueryWrapper<HazardExamineTeam>().in(HazardExamineTeam::getExamineTeamId,list));
	}

    /**
    * 物理删除
    * @author zhangwei
    * @date 2024-09-02 11:25:48
    * @param hazardExamineTeamIds hazardExamineTeamIds
    */
    @Override
    @Transactional
    public void physicallyDeleteHazardExamineTeam(String hazardExamineTeamIds) {
        List<String> list = Arrays.asList(hazardExamineTeamIds.split(StringPool.COMMA));
        LambdaQueryWrapper<HazardExamineTeam> wapper = new LambdaQueryWrapper<>();
        wapper.in(HazardExamineTeam::getExamineTeamId,list);
        this.remove(wapper);
    }
}
